package com.firewolf.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.firewolf.service.UserService;

@Controller
@RequestMapping("shiro")
public class ShiroHandler {
	
	@Autowired
	private UserService service;
	
	@RequestMapping("login")
	public String login(@RequestParam("username") String username,@RequestParam("password") String password,HttpSession session){
		
		Subject subject = SecurityUtils.getSubject();
		if(!subject.isAuthenticated()){
			UsernamePasswordToken token = new UsernamePasswordToken(username,password);
			try{
				subject.login(token);
			}catch (AuthenticationException ae) {
				System.out.println("登录失败: " + ae.getMessage());
			}
		}
		return "redirect:/list.jsp";
	}
	
	/**
	 * 测试Session，在控制层设置Session，到Service一样可以访问到
	 * @param session
	 * @return
	 */
	@RequestMapping("testSession")
	public String testSession(HttpSession session){
		session.setAttribute("username", "liuxing");
		service.testSession();
		return "redirect:/list.jsp";
	}
}
